package com.example.demo.util;


import com.example.demo.pojo.Person;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class YamlUtil {
    private static Yaml yaml = new Yaml();

    public static void read(String path) {
        File dumpFile = new File(path);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(dumpFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Person father = yaml.loadAs(inputStream, Person.class);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(father.getName())
                .append("\t")
                .append(father.getSex())
                .append("\t")
                .append(father.getAge())
                .append("\t")
                .append(father.getChildren().size());
        System.out.println(stringBuilder.toString());
        System.out.println(father);
    }

    public static void write(String path) {
        Person father = new Person();
        father.setName("simon.zhang");
        father.setAge(21);
        father.setSex("man");
        List<Person> children = new ArrayList<Person>();
        for (int i = 8; i < 10; i++) {
            Person child = new Person();
            if (i % 2 == 0) {
                child.setSex("man");
                child.setName("mary" + (i - 7));
            } else {
                child.setSex("fatel");
                child.setName("simon" + (i - 7));
            }
            child.setAge(i);
            children.add(child);
        }
        father.setChildren(children);
        /* Export data to a YAML file. */
        try {
            yaml.dump(father, new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
